<template>
  <div class="edit-container">
    <el-form v-loading="formLoading" ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="标题" class="col"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input type="number" placeholder="排序" v-model="form.sort" class="col" maxlength="5"/>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <Tinymce v-model="form.content"></Tinymce>
      </el-form-item>
      <el-form-item>
        <el-button v-loading="saveLoading" element-loading-background="rgba(0, 0, 0, 0.3)" type="primary"
                   @click="handlerSubmit" v-has-permi="['admin:demo:save']">保存
        </el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {detail, save} from "@/api/demo";
import {getForm} from "@/utils/utils";
import Tinymce from "@/components/Tinymce/index.vue";

export default {
  components: {Tinymce},
  props: {
    id: {
      default: null
    }
  },
  data() {
    return {
      form: {
        id: null,
        title: '',
        content: '',
        sort: '',
      },
      rules: {
        title: [{required: true, message: '请填写标题', trigger: ['blur']}],
        content: [{required: true, message: '请填写内容', trigger: ['blur']}],
      },
      roles: [],
      saveLoading: false,
      formLoading: false,
      uploads: {
        show: false,
        multiple: true,
      }
    }
  },
  mounted() {
    if (this.id) {
      this.getDetail();
    }
  },
  methods: {
    getDetail() {
      this.formLoading = true
      detail(this.id).then(res => {
        getForm(res, this.form);
      }).finally(() => {
        this.formLoading = false;
      })
    },
    handlerSubmit() {
      if (this.saveLoading || this.formLoading) {
        return;
      }
      this.$refs.form.validate(valid => {
        if (!valid) return;
        this.saveLoading = true;
        save(this.form).then(() => {
          this.$message.success('保存成功');
          this.close();
        }).finally(() => {
          this.saveLoading = false
        })
      })
    },
    close() {
      this.$emit('hideEditDialog')
    }
  }
}
</script>
